/* eslint-disable no-undef */
/* eslint-disable array-callback-return */

import { message } from 'antd';
import router from 'umi/router';
import {
  increasePersonnelList,
  getProList,
  getProDetail,
  getFeedback,
  personnelexport,
  pespersonnelexport,
  freceiptfile,
  lookagreement,
  receiptinface,
  notifyctring,
  backReceipt,
  receiptModification,
  getReceiptTagList,
  orderDetails,
  paymentDetailsList,
  getproselectedList,
  getcustNamesList,
  getSupplyList,
  getTwohouseMessage,
  getbatchConnec,
  getBatchAcceList,
  getEmpContact,
  getInsIdeDetail,
  updateInsIdeReceipt,
  insertEmpContact,
} from '@/services/receiveordermanage';

export default {
  state: {
    formFieldsValue: {},
    expandForm: false,
    activeKey: '1',
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    dataList: [],
    detail: {
      detList: [],
      affixList: [],
    },
    proFbList: [],
    proBaseList: {},
    addOrEdit: {
      productList: [],
    },
    history: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    servicnftio: [], // 服务类型
    pdInfoDtos: [], // 产品服务信息
    detailsData: {},
    payDetailsData: [],
    proInsuranceList: [],
    supplyList: [],
    contList: [], // 客户下拉
    stafflxList: {},
    secAccuList: [], // 工伤二级户
    tabList: [
      { itemCode: '1', itemName: '待接单', isHas: false },
      { itemCode: '2', itemName: '已接单', isHas: false },
      { itemCode: '3', itemName: '已回单', isHas: false },
      { itemCode: '4', itemName: '问题人员', isHas: false },
      { itemCode: '5', itemName: '已取消', isHas: false },
    ],
    empContactList: {}, // 获取员工联系详情数据
    switch: true,
    insFlag: null,
  },
  effects: {
    // 待接单查看详情
    *feactorderDetail({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(orderDetails, payload);
      const sortNumber = (a, b) => a.operLeafType - b.operLeafType;
      if (response.success) {
        if (response.data.execStatusDto && response.data.execStatusDto.leafList) {
          response.data.execStatusDto.leafList = response.data.execStatusDto.leafList.sort(
            sortNumber
          );
        }
        yield put({
          type: 'orderDetails',
          payload: response.data,
        });
      }
      callback(response);
    },
    // 获取缴纳明细列表
    *getcustNamesList({ payload, callback }, { call, put }) {
      const response = yield call(getcustNamesList, payload);
      if (response.success) {
        yield put({
          type: 'getCustDataList',
          payload: response.data,
        });
      }
      return callback && callback(response);
    },

    // 获取缴纳明细列表
    *getPaymentDetails({ payload }, { call, put }) {
      const response = yield call(paymentDetailsList, payload);
      if (response.success) {
        yield put({
          type: 'getPayDataList',
          payload: response.data,
        });
      } else {
        message.warning('查询失败！');
      }
    },

    // 获取问题对象的险种
    *selectedRowsList({ payload }, { call, put }) {
      const payloads = {
        recvAddTaskIds: payload,
      };
      const response = yield call(getproselectedList, payloads);
      if (response.success) {
        yield put({
          type: 'getProInsuranceList',
          payload: response,
        });
      } else {
        message.warning(response.message || '查询失败！');
      }
    },

    // 列表数据
    *fetchList({ payload }, { call, put }) {
      const response = yield call(increasePersonnelList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: response.data || [],
          currentPage,
          pageSize,
        },
      });
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;

      yield put({
        type: 'getProList',
        payload: {
          data: response.data || [],
          currentPage,
          pageSize,
        },
      });
    },
    // 问题人员详情
    *feactProDetail({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback = () => {} }, { call }) {
      const response = yield call(getFeedback, payload);
      callback(response);
    },

    // 回单
    *receiptId({ payload, callback }, { call }) {
      const response = yield call(backReceipt, payload);
      if (callback) {
        callback(response);
      }
    },

    // 回单修改
    *modification({ payload, callback }, { call }) {
      const response = yield call(receiptModification, payload);
      if (callback) {
        callback(response);
      }
    },

    // 已接单文件导出
    *outexportFile({ payload }, { call }) {
      const response = yield call(personnelexport, payload);
      const blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
      } else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = payload.fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    },

    // 接单
    *receiptFile({ payload, callback }, { call }) {
      const response = yield call(freceiptfile, payload);
      callback(response);
    },

    // 查看协议
    *seeagreement({ payload, callback }, { call, put }) {
      // debugger
      const response = yield call(lookagreement, payload);
      // const {} = payload;
      if (response.success) {
        yield put({
          type: 'getseeagreementList',
          payload: { data: response.data },
        });
      } else {
        yield put({
          type: 'getseeagreementList',
          payload: { data: [] },
        });
      }
      callback(response);
    },

    *notifyc({ payload, callback }, { call }) {
      const response = yield call(notifyctring, payload);
      callback(response);
    },

    // 回单
    *receiptback({ payload, callback }, { call, put }) {
      const response = yield call(receiptinface, payload);
      if (response.success) {
        const receFlagList = [];
        const assFlagList = [];
        let insFlag = null;
        if (response.data && response.data.pdInfoDtos) {
          response.data.pdInfoDtos.map(item => {
            receFlagList.push(item.receFlag);
          });
        }

        if (response.data && response.data.setInfos) {
          response.data.setInfos.map(item => {
            assFlagList.push(item.receFlag);
          });
        }

        if (assFlagList.indexOf(1) > -1) {
          insFlag = 2;
        } else {
          insFlag = 1;
        }
        if (receFlagList.indexOf(2) === -1) {
          router.goBack();
        } else {
          yield put({
            type: 'receiptinfacemessage',
            payload: { data: response.data, insFlag },
          });
        }
      } else {
        message.warning(response.message || '查询失败');
      }
      callback(response);
    },

    // 查询页签数量
    *getReceiptTagData({ payload, callback }, { call }) {
      const response = yield call(getReceiptTagList, payload);
      if (response.success) {
        if (callback) {
          callback(response.data);
        }
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取供应商列表
    *fetchSupplyList({ payload }, { call, put }) {
      const response = yield call(getSupplyList, payload);
      yield put({
        type: 'getSupplyList',
        payload: Array.isArray(response.data) ? response.data : [],
      });
    },

    // 问题人员文件导出
    *quesoutexportFile({ payload }, { call }) {
      const response = yield call(pespersonnelexport, payload);
      const blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
      } else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = payload.fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    },

    // 获取工伤二级户数据
    *getTwohouseData({ payload, callback }, { call, put }) {
      const response = yield call(getTwohouseMessage, payload);
      if (response.success) {
        if (response.data.flag) {
          yield put({
            type: 'getTwohouseDatas',
            payload: response.data,
          });
        }

        if (callback) {
          callback(response.data);
        }
      } else {
        message.warning('查询失败！');
      }
    },
    *batchConnec({ payload, callback }, { call }) {
      const response = yield call(getbatchConnec, payload);
      if (response.success) {
        message.success('接单成功！');
        callback(response);
      } else {
        message.warning(response.message || '接单失败！');
        callback(response);
      }
    },

    // 批量接单
    *batchAcce({ payload, callback }, { call }) {
      const response = yield call(getBatchAcceList, payload);
      return callback && callback(response);
    },
    // 获取页签数量
    *fetchTabNum({ payload }, { call, put, select }) {
      const response = yield call(getReceiptTagList, payload.formFieldsValue);
      let activeKey = yield select(state => state.addemprec.activeKey);
      const tabList = yield select(state => state.addemprec.tabList);
      if (response.success) {
        if (response.data && response.data.length) {
          const sortNumber = (a, b) => a.itemCode - b.itemCode;
          const tabCodeArr = response.data.sort(sortNumber);
          const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.tabHdl}` === activeKey); // 当前页签有没有查询到
          if (!isHasBadgeCurrentTab) {
            activeKey = `${tabCodeArr[0].tabHdl}`;
          }
          tabCodeArr.forEach(item => {
            if (`${item.tabHdl}` !== activeKey) {
              tabList[item.tabHdl - 1].isHas = true;
            }
          });
          yield put({
            type: 'updateModalData',
            payload: { activeKey, tabList },
          });
          const getListParams = {
            ...payload.formFieldsValue,
            pageArg: { currentPage: payload.currentPage, pageSize: payload.pageSize },
          };
          if (activeKey === '4') {
            yield put({
              type: 'fetchProList',
              payload: { ...getListParams, busiType: '1' },
            });
          } else {
            yield put({
              type: 'fetchList',
              payload: { ...getListParams, hdlState: activeKey },
            });
          }
        } else {
          yield put({
            type: 'getList',
            payload: {
              data: { pagerVo: {} },
              currentPage: 1,
              pageSize: 10,
            },
          });
        }
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },

    // 获取员工联系详情信息  author-xxl
    *getEmpContactDetail({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getEmpContact, payload);
      if (response.success) {
        yield put({
          type: 'getEmpContact',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '获取员工联系信息：服务器端错误');
      }
      callback(response.data);
    },
    // 获取缴费人员类别信息 author-xxl
    *getInsIdeList({ payload }, { call }) {
      const response = yield call(getInsIdeDetail, payload);
      return response;
    },
    // 修改缴费人员类别 author-xxl
    *updateInsIde({ payload }, { call }) {
      const response = yield call(updateInsIdeReceipt, payload);
      return response;
    },
    // 员工联系提交数据 author-xxl
    *insertEmpContact({ payload, callback = () => {} }, { call }) {
      const response = yield call(insertEmpContact, payload);
      callback(response);
    },
  },

  reducers: {
    // 查看列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pagerVo.pageRecords) ? data.pagerVo.pageRecords : [];
      const { countVo } = data;
      return {
        ...state,
        data: {
          list,
          countVo,
          pagination: { total: data.pagerVo.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 查看协议
    getseeagreementList(
      state,
      {
        payload: { data },
      }
    ) {
      const list = Array.isArray(data) ? data : [];
      return {
        ...state,
        data: {
          list,
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      };
    },

    // 回单
    receiptinfacemessage(
      state,
      {
        payload: { data, insFlag },
      }
    ) {
      return {
        ...state,
        data,
        insFlag,
      };
    },

    dicList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        servicnftio: data,
      };
    },

    // 获取问题人员列表
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos,
      };
    },

    // 发单增员 - 详情
    orderDetails(state, { payload }) {
      return {
        ...state,
        detailsData: payload,
      };
    },
    // 点击缴纳明细时
    getPayDataList(state, { payload }) {
      return {
        ...state,
        payDetailsData: payload,
      };
    },

    // 文件导出
    exportFile(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos,
      };
    },

    // 取消分项
    newpdInfoDtosList(state, { payload }) {
      const temp = state;
      temp.data.pdInfoDtos = payload;
      return {
        ...state,
        data: state.data,
      };
    },
    // 分项
    addpdInfoDtosList(state, { payload }) {
      const temp = state;
      temp.data.pdInfoDtos = payload;
      return {
        ...state,
        data: state.data,
      };
    },
    // 客户下拉数据
    getCustDataList(state, { payload }) {
      return {
        ...state,
        contList: payload,
      };
    },

    // 标记问题人员的问题对象列表
    getProInsuranceList(state, { payload }) {
      return {
        ...state,
        proInsuranceList: payload.data,
      };
    },
    getSupplyList(state, { payload }) {
      return {
        ...state,
        supplyList: payload,
      };
    },

    // 工伤二级户
    getTwohouseDatas(state, { payload }) {
      if (payload.injSecList.length > 0) {
        payload.injSecList.map(item => {
          const temp = item;
          temp.value = temp.accoId;
          temp.label = temp.accoName;
          temp.children = temp.injSecAccoDtos;
        });
      }

      if (payload.injSecList.length > 0) {
        payload.injSecList.map(it => {
          it.children.map(items => {
            const temp = items;
            temp.value = temp.injSecAccoId;
            temp.label = temp.injSecAccoName;
          });
        });
      }
      return {
        ...state,
        secAccuList: payload.injSecList,
      };
    },

    // 获取员工联系详情信息
    getEmpContact(state, { payload }) {
      return {
        ...state,
        empContactList: payload,
      };
    },

    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHas = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },
  },
};
